#! /usr/bin/env python
# coding=utf-8
#############################################################################
#                                                                           #
#   File: common.py                                                         #
#                                                                           #
#   Copyright (C) 2008-2009 Du XiaoGang <dugang@188.com>                    #
#                                                                           #
#   Home: http://gappproxy.googlecode.com                                   #
#                                                                           #
#   This file is part of GAppProxy.                                         #
#                                                                           #
#   GAppProxy is free software: you can redistribute it and/or modify       #
#   it under the terms of the GNU General Public License as                 #
#   published by the Free Software Foundation, either version 3 of the      #
#   License, or (at your option) any later version.                         #
#                                                                           #
#   GAppProxy is distributed in the hope that it will be useful,            #
#   but WITHOUT ANY WARRANTY; without even the implied warranty of          #
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the           #
#   GNU General Public License for more details.                            #
#                                                                           #
#   You should have received a copy of the GNU General Public License       #
#   along with GAppProxy.  If not, see <http://www.gnu.org/licenses/>.      #
#                                                                           #
#############################################################################

import os, sys, urllib2, time, Queue

def we_are_frozen():
    """Returns whether we are frozen via py2exe.
    This will affect how we find out where we are located."""

    return hasattr(sys, "frozen")

def module_path():
    """ This will get us the program's directory,
    even if we are frozen using py2exe"""

    if we_are_frozen():
        return os.path.dirname(sys.executable)
    return os.path.dirname(__file__)

class ConfigVars:
    _dir = module_path()
    VERSION = "1.2.0"
    GOOGLE_PROXY = None
    LISTEN_PORT = None
    LOCAL_PROXY = ''
    FETCH_SERVER = ''
    CONF_FILE = None
    CERT_FILE = None
    KEY_FILE  = None
    PROTOCOL = None
    HTTPS_ENABLE = True
    IPV6_ENABLE = False
    IPV6_GOOGLE = []
    IPV4_GOOGLE = []
    def __init__(self):#this is just giving default values
        self._make_default()
    def _make_default(self):
        self.GOOGLE_PROXY = 'www.google.cn:80'
        self.LISTEN_PORT = 8000
        self.LOCAL_PROXY = ''
        self.FETCH_SERVER = ''
        self.CONF_FILE = os.path.join(self._dir, 'proxy.conf')
        self.CERT_FILE = os.path.join(self._dir, 'ssl/LocalProxyServer.cert')
        self.KEY_FILE  = os.path.join(self._dir, 'ssl/LocalProxyServer.key')
        self.GOOGLE_FRONTEND_FILE = os.path.join(self._dir, 'GoogleFrontEndIP.conf')
        self.PROTOCOL = 4#ipv4
        self.FETCH_CORE = None
    
    def readConf(self):
        # read config file
        try:
            fp = open(self.CONF_FILE, "r")
        except IOError:
            # use default parameters
            return
        # parse user defined parameters
        while True:
            line = fp.readline()
            if line == "":
                # end
                break
            # parse line
            line = line.strip()
            if line == "": # empty line
                continue
            if line.startswith("#"):# comments
                continue
            (name, sep, value) = line.partition("=")
            if sep == "=":
                name = name.strip().lower()
                value = value.strip()
                if name == "listen_port":
                    self.LISTEN_PORT = int(value)
                elif name == "local_proxy":
                    self.LOCAL_PROXY = value
                elif name == "fetch_server":
                    self.FETCH_SERVER = value
                elif name == "ipv6_enable":
                    if value.lower() == "true":
                        self.IPV6_ENABLE = True
                    else:
                        self.IPV6_ENABLE = False
                elif name == "protocol":
                    if value.lower() == "ipv4":
                        self.PROTOCOL = 4
                    else:
                        self.PROTOCOL = 6
                elif name == "https_enable":
                    if value.lower() == "true":
                        self.HTTPS_ENABLE = True
                    else:
                        self.HTTPS_ENABLE = False
        if self.HTTPS_ENABLE == True:
            self.FETCH_SERVER = "https://"+self.FETCH_SERVER 
        else:
            self.FETCH_SERVER = "http://"+self.FETCH_SERVER 
        fp.close()
        
    def writeConf(self):
        fp = open(self.CONF_FILE, "w")
        if self.PROTOCOL == 4:
            protocol = "IPV4"
        else:
            protocol = "IPV6"
           
        configPairs = {"LISTEN_PORT":str(self.LISTEN_PORT),
                       "LOCAL_PROXY":str(self.LOCAL_PROXY),
                       "FETCH_SERVER":str(self.FETCH_SERVER),
                       "IPV6_ENABLE":str(self.IPV6_ENABLE),
                       "HTTPS_ENABLE":str(self.HTTPS_ENABLE),
                       "PROTOCOL":protocol}
        for key in configPairs:
            fp.write("%s = %s\n" % (key,configPairs[key]))
        fp.close()


    def readGoogleFrontEndIP(self):
        fp = open(self.GOOGLE_FRONTEND_FILE,'r')
        appendingList = None
        for line in fp:
            stripedLine = line.strip()
            if stripedLine.startswith('#') or stripedLine == '':
                continue
            if stripedLine == "-IPV4":
                appendingList = self.IPV4_GOOGLE
                continue
            if stripedLine == "-IPV6":
                appendingList = self.IPV6_GOOGLE
                continue
            try:
                appendingList.append(stripedLine)
            except:
                raise
            

globalVars = ConfigVars()
globalVars.readConf()
globalVars.readGoogleFrontEndIP()

def getTimeStr(fmt = "%Y/%m/%d %H:%M:%S"):
    return time.strftime(fmt)
    
logQueue = Queue.Queue()

def logger(level,position, message, address = ""):#level 0 critical 1 error 2 warning 3 info
    log_type = ["critical","error","warning","info"]
    if level < 4:
        logQueue.put("[%s]%s<%s>\t%s %s" %(log_type[level],getTimeStr(),position,message,address))

def printLog():
    try:
        while True:
            entry = logQueue.get(block = False)
            print entry
    except Queue.Empty:
        pass
        
    

def getGlobalVars():
    return globalVars

class GAppProxyError(Exception):
    def __init__(self, reason):
        self.reason = reason

    def __str__(self):
        return '<GAppProxy Error: %s>' % self.reason
